let f = floaty.rawWindow(
  <vertical>
    <frame w="{{parseInt(device.width*0.63)+'px'}}" h="{{device.height*0.3+'px'}}">
      <webview id="web" bg="#00000000" />
    </frame>
    <img id="bar" bg="#50E09F00" h="50px"/>
  </vertical>);

ui.run(() => {
  let mimiUrl = "https://mi.js.org/live2d-widget/demo/demo.html";
  let tag = "loadOK";
  let init = 'if (screen.width < 768) {'
  +'  Promise.all(['
  +'    loadExternalResource(live2d_path + "waifu.css", "css"),'
  +'    loadExternalResource(live2d_path + "live2d.min.js", "js"),'
  +'    loadExternalResource(live2d_path + "waifu-tips.js", "js")'
  +'  ]).then(() => {'
  +'    initWidget({'
  +'      waifuPath: live2d_path + "waifu-tips.json",'
  +'      cdnPath: "https://cdn.jsdelivr.net/gh/fghrsh/live2d_api/"'
  +'    });'
  +'  });'
  +'}'
  // 删除右上角的github
  +'document.getElementsByTagName("body")[0].removeChild(document.getElementById("github"));'
  // 设置url带有auto参数
  +setUrlDataFromWeb.toString()
  +';setUrlDataFromWeb("'+tag+'");'

  f.web.setBackgroundColor(0);
  f.web.getBackground().setAlpha(0);
  f.web.loadUrl(mimiUrl);

  // 监控地址
  setInterval(()=>{
    if(false && f.web.url.indexOf(mimiUrl) < 0){
      f.web.stopLoading();
      if(confirm("不要离开我~\n是否重新载入？")){
        f.web.loadUrl(mimiUrl);
        initFun();
      }
    }
  },3000);

  // 初始化
  initFun();
  function initFun(){
    let inte = setInterval(() => {
      if(getUrlData(f.web) == tag) {
        runUrlDataByWeb(f.web,
          // 放大
          'document.getElementsByTagName("body")[0].style.zoom=3;'
          )
        clearInterval(inte);
      }
      runUrlDataByWeb(f.web,init);
    }, 200);
  }

        // { '0': 'https://oss.ucdl.pp.uc.cn/fs01/union_pack/PPAssistant_2522676_PP_247.apk?x-oss-process=udf%2Fpp-udf%2CJjc3LiMnJ3R%2Bf35%2B&apprd=39899',
        // '1': 'Mozilla/5.0 (Linux; Android 11; RMX2072 Build/RKQ1.200710.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36',
        // '2': 'attachment;filename=PPAssistant_2522676_PP_247.apk',
        // '3': 'application/vnd.android.package-archive',
        // '4': 14798422 }
        // 链接，浏览器信息，文件名，mime接口类型，总长度
        // String url, String userAgent, String contentDisposition,String mimetype, long contentLength
  // 设置下载监听器
  f.web.setDownloadListener(function (data, deviceInfo, notknow1, type, notknow2) {
    if (type == "image/png")
      threads.start(function () {
        if (confirm("是否保存图片？")){
          files.ensureDir("/sdcard/脚本/米米的看板娘/");
          log(images.fromBase64(data).saveTo("/sdcard/脚本/米米的看板娘/"
                                + new Date().toLocaleString()+".png"));
        }
      });
  });
});

OnTouchListener(f,"bar",{
  dwonCode: 'setColor("#50117ACC");',
  moveLongClickCode: 'setColor("#50DC4C3F");',
  upSuf: 'setColor("#50E09F00");',
  upClickCode: 'toast("样品\\n成品正在...\\n长按关闭");',
  upLongClickCode: 'exit();',
  moveCode: 'let newX=fx+(event.getRawX()-downX);'//新的x坐标
  +'let newY=fy+(event.getRawY()-downY);'//新的y坐标
  +'f.setPosition(newX,newY);'//移动
});

// 续命
setInterval(()=>{},100000);

function setColor(str) {
  ui.run(()=>{
    f.bar.setBackgroundColor(colors.parseColor(str));
  })
}

function OnTouchListener(f,viewID,code){try{ eval("ViewObj=f."+viewID+";"); if(ViewObj==undefined) throw "在悬浮窗中未获取到id为\""+viewID+"\"+的视图组件"; }catch(err){ return false; } attributeDefined(code, [ ["scope", "10"] ,["longTime", "600"] ,["initCode"] ,["dwonCode"] ,["moveCode"] ,["moveLongClickCode"] ,["upMoveCode"] ,["upLongClickCode"] ,["upClickCode"] ,["upPre"] ,["upSuf"] ] ); var fx=fy=downX=downY=downTime=0; var longPress=true, moveLongClickTag = true; eval(code.initCode); ViewObj.setOnTouchListener( function(view, event){ switch(event.getAction()){ case event.ACTION_DOWN: ViewObj.setAlpha(ViewObj.alpha*0.8); downX = event.getRawX(); downY = event.getRawY(); fx=f.getX(); fy=f.getY(); downTime = new Date().getTime(); longPress=true; eval(code.dwonCode); return true; case event.ACTION_MOVE: if(Math.abs(event.getRawX()-downX)>code.scope||Math.abs(event.getRawY()-downY)>code.scope){ longPress=false; } if(moveLongClickTag && new Date().getTime()-downTime>code.longTime){ moveLongClickTag=false; eval(code.moveLongClickCode);} eval(code.moveCode); return true; case event.ACTION_UP: ViewObj.setAlpha(ViewObj.alpha*1.25); moveLongClickTag=true; eval(code.upPre); if( new Date().getTime()-downTime<code.longTime ){ longPress=false; } if( Math.abs(event.getRawX()-downX)>code.scope||Math.abs(event.getRawY()-downY)>code.scope ){ eval(code.upMoveCode); }else{ if(longPress){ eval(code.upLongClickCode); }else{ eval(code.upClickCode);} } eval(code.upSuf); return true; } return true; } ); function attributeDefined(obj, arr) { try { arr.forEach(a => { if (a != undefined && eval("(obj." + a[0] + ")") == undefined) { if (a.length == 1) a.push(""); eval("obj." + a[0] + "=\"" + a[1] + "\""); } }); } catch (e) { log(e) } return obj; } }
function getAttributeByObject(obj) {

  if (typeof re != "object") re = {};
  if (typeof obj != "object") return re;

  let name;
  for (let key in obj) {
      try {
          name = typeof obj[key];
      } catch (e) {
          console.error(e)
          name = "accident";
      }
      if (typeof re[name] != "object")
          re[name] = [];
      re[name].push(key);
  }

  return re;
}
function setUrlDataFromWeb(data, tag) {

  switch (typeof data) {
      case "string": break;
      case "object": data = JSON.stringify(data); break;
      default: throw "参数不是字符串或者对象类型！";
  }
  tag = tag || "?auto.js=";
  if (data.length > 2048)
      console.warn("参数过长，可能会引发异常。");
  window.history.pushState("", "", tag + data);
}
function getUrlData(action, tag) {

  try {
      tag = tag || '?auto.js=';
      let startIndexOf = action.url.indexOf(tag);
      if (startIndexOf < 0) throw "未获取到参数";
      // 拿到数据
      let data = action.url.substring(startIndexOf + tag.length);
      // 还原地址
      setUrlNotLoad(action, action.url.substring(0, startIndexOf));
      return decodeURIComponent(data);
  } catch (e) {
      console.warn(e);
  }
  return false;
}
function runUrlDataByWeb(action, code) {
  action.loadUrl("javascript:" + code);
}
function setUrlNotLoad(action, url) {
  action.loadUrl("javascript:window.history.pushState('','', " + url + ");");
}